<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <div class="lg:w-2/12 w-full h-full p-2 shadow">
      <div class="flex flex-col w-full h-full">
        <a-input-group class="mb-2 w-full" size="mini">
          <a-input placeholder="" allow-clear @input="changeKeyword" @clear="resetData"/>
          <a-button
            @click="() => {
              isExpand ? treeRef.expandAll(false) : treeRef.expandAll(true)
              isExpand = ! isExpand
            }"
          >
            {{ isExpand ? '折叠' : '展开' }}
          </a-button>
        </a-input-group>
      </div>
      <div ref="leftSideContainerRef" class="w-full" style="overflow-y: auto;">
        <a-tree
          ref="treeRef"
          :data="treeDatas"
          :field-names="{ children: 'children', title: 'name', key: 'id' }"
          @select="onSelect"
        />
      </div>
    </div>
    <div class="lg:w-10/12 w-full lg:ml-4 mt-5 lg:mt-0">
      <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
        <a-layout-content class="flex flex-col lg:h-full relative w-full">
          <div ref="searchRef">
            <a-row v-if="showSearch" class="table-search mb-3">
              <a-col :flex="1">
                <a-form
                  :model="query"
                  layout="inline"
                  label-align="left"
                >
                  <a-row :gutter="16">
                    <a-col flex="220px">
                      <a-input v-model="query.ip" placeholder="请输入IP" allow-clear>
                        <template #prepend>名称</template>
                      </a-input>
                    </a-col>
                    <a-col flex="360px">
                      <a-input-group>
                        <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                          <a-option value="created_at" label="添加时间" />
                        </a-select>
                        <a-range-picker v-model="query.range_date" allow-clear/>
                      </a-input-group>
                    </a-col>
                  </a-row>
                </a-form>
              </a-col>
              <a-col :flex="'86px'" style="text-align: right">
                <a-space :size="6">
                  <a-button type="primary" @click="search">
                    <template #icon><icon-search /></template>搜索
                  </a-button>
                  <a-button @click="refresh()">
                    <template #icon><icon-refresh /></template>重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </div>
          <div class="table-header lg:flex justify-between mb-2">
            <a-space class="lg:flex block lg:inline-block">
              <a-button v-auth="['adminlog/delete']" type="primary" status="danger" size="small" @click="batchDel()">
                <template #icon><icon-delete /></template>批量删除
              </a-button>
            </a-space>
            <a-space class="lg:mt-0 mt-2">
              <a-tooltip content="刷新表格"><a-button shape="circle" @click="refresh"><icon-refresh /></a-button></a-tooltip>
              <a-tooltip content="显隐搜索"><a-button shape="circle" @click="toggleSearch"><icon-search /></a-button></a-tooltip>
              <a-tooltip content="设置"><a-button shape="circle" @click="setTableColumns"><icon-settings /></a-button></a-tooltip>
            </a-space>
          </div>
          <div ref="tableContainerRef">
            <a-table
              ref="tableRef"
              row-key="id"
              :loading="loading"
              :pagination="pagination"
              :data="renderData"
              :bordered="{ wrapper: true, cell: true }"
              :row-selection="rowSelection"
              :scroll="tableScroll"
              column-resizable
              @selection-change="selectionChange"
              @page-change="onPageChange"
              @page-size-change="onPageSizeChange"
            >
              <template #columns>
                <vue-table-column :columns="columns">
                  <template #operations="{ record }">
                    <a-button v-auth="['adminlog/delete']" type="primary" status="danger" size="small" @click="del([record])"><template #icon><icon-delete /></template>删除</a-button>
                  </template>
                </vue-table-column>
              </template>
            </a-table>
          </div>
        </a-layout-content>
      </a-spin>
    </div>

    <SetColumn ref="setColumnRef" :columns="columns" @update:columns="updateColumns"/>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, nextTick, onMounted, onUnmounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight } from '@/utils/index';
  import tool from '@/utils/tool';
  import { apiList, apiDel } from '@/api/admin-log';
  import { apiTreeList as apiMenuTree } from '@/api/admin-menu';
  import VueTableColumn from '@/components/table/table-column.vue';
  import SetColumn from '@/components/table/set-column.vue';

  const { loading, setLoading } = useLoading(false);
  const basePagination = {
    current: 1,
    pageSize: 20,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 50, 100, 150, 200, 300, 500],
  };
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      name: '',
      time_type: 'created_at',
      range_date: [],
    };
  };
  const baseColumns = [
    {
      title: 'ID', dataIndex: 'id', width: 80,
      align: 'center', fixed: 'left',
      sortable: {sortDirections: ['ascend', 'descend']},
    },
    {
      title: '操作IP', dataIndex: 'ip',  width: 120,
      align: 'center',
    },
    {
      title: '操作详细', dataIndex: 'info',  width: 300,
      align: 'center',
      ellipsis: true, tooltip: true,
    },
    {
      title: '创建时间', dataIndex: 'created_at', width: 180,
      align: 'center',
      sortable: {sortDirections: ['ascend', 'descend']},
    },
    {
      title: '操作', dataIndex: 'operations', width: 80,
      align: 'center', fixed: 'right',
      slotName: 'operations',
    },
  ];
  const columns = ref(tool.local.get('columns-templete') || baseColumns);
  const renderData = ref([]);
  const query = ref(baseQuery());
  const pagination = reactive({
    ...basePagination,
  });
  const rowSelection = reactive({
    type: 'checkbox',
    selectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();
  const setColumnRef = ref();
  const searchHeight = ref(0);

  const isReset = ref(true); // 是否重置
  let selectionKeys = []; // 选中项ID
  const spinLoading = ref(false);
  const spinTip = ref();

  const leftSideContainerRef = ref();
  const treeRef = ref();
  const isExpand = ref(false);
  const baseTreeDatas = ref();
  const treeDatas = ref();

  const settingFixedPage = () => {
    const workHeight = workAreaHeight();
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
    const leftSideHeight = workHeight - 0;
    leftSideContainerRef.value.style.height = `${leftSideHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };
  const toggleSearch = async () => {
    const dom = searchRef.value?.style;
    if (dom) {
      showSearch.value = !showSearch.value;
      await nextTick(() => {
        searchHeight.value = searchRef.value.offsetHeight;
        settingFixedPage();
      });
    }
  };
  const setTableColumns = () => {
    setColumnRef.value.init();
  };
  const updateColumns = (data) => {
    columns.value = data;
    tool.local.set('columns-templete', columns.value);
  };

  // 分页
  const onPageChange = async (page) => {
    isReset.value = false;
    await fetchData({ ...query.value, page });
  };
  const onPageSizeChange = async (limit) => {
    isReset.value = false;
    await fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params = { ...query.value }
  ) => {
    setLoading(true);
    await reset();
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row = {}) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].id} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h('div', { innerHTML: message }),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {

          } finally {
            await fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 搜索
  const search = async () => {
    query.value.page = 1;
    await fetchData({...query.value});
  };
  // 刷新
  const refresh = async () => {
    query.value = baseQuery();
    await fetchData({...query.value});
  };
  const getMenus = async () => {
    const { data } = await apiMenuTree();
    baseTreeDatas.value = data.data;
    treeDatas.value = data.data;
  };

  const changeKeyword = (keyword) => {
    if (!keyword || keyword === '') {
      treeDatas.value = Object.assign(baseTreeDatas.value, []);
      return false;
    }
    treeDatas.value = searchNode(keyword);
  }
  const resetData = () => {
    treeDatas.value = baseTreeDatas.value;
  };
  const searchNode = (keyword) => {
    const loop = (data) => {
      let tree = [];
      data.map(item => {
        if (item.children && item.children.length > 0) {
          const temp = loop(item.children);
          tree.push(...temp);
        } else if (item['name'].indexOf(keyword) !== -1) {
          tree.push(item);
        }
        return tree;
      })
      return tree;
    }
    return loop(baseTreeDatas.value);
  }
  const onSelect = (selectedKeys) => {

  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys;
  };
  const selectMsg = (message) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  onMounted(async () => {
    await fetchData();
    await getMenus();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'Template',
  };
</script>

<style scoped lang="less">
  :deep(.arco-tree-node:hover) {
    background-color: var(--color-fill-2);
    border-radius: 3px;
  }
  :deep(.arco-tree-node-switcher) {
    margin-left: 2px;
  }
</style>
